// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <deque>
#include <mutex>
#include <pollux/common/future/pollux_promise.h>

namespace kumo::pollux::common {
    /// A generic admission controller that can be used to limit the number of
    /// resources in use and can log metrics like resource usage, queued count,
    /// queued wait times. When a calling thread's request for resources surpasses
    /// the set limit, it will be placed in a FIFO queue. The thread must then wait
    /// until sufficient resources are freed by other threads, addressing all
    /// preceding requests in the queue, before its own request can be granted.
    class AdmissionController {
    public:
        struct Config {
            /// The maximum number of resource units that can be used at any given time.
            /// Set to a default value of max unit64 to signify unlimited limit.
            uint64_t maxLimit{std::numeric_limits<uint64_t>::max()};
            /// The metric name for resource usage. If not set, it will not be reported.
            /// Should be a registered as a average metric.
            std::string resourceUsageAvgMetric;
            /// The metric name for resource queued count. If not set, it will not be
            /// reported. Should be a registered as a count metric.
            std::string resourceQueuedCountMetric;
            /// The metric name for resource queued wait time. If not set, it will not
            /// be reported. Should be a registered as a histogram metric.
            std::string resourceQueuedTimeMsHistogramMetric;
        };

        explicit AdmissionController(const Config &config) : config_(config) {
        }

        // Accept can block until sufficient resources are freed by other threads.
        void accept(uint64_t resourceUnits);

        void release(uint64_t resourceUnits);

        uint64_t currentResourceUsage() const {
            std::lock_guard<std::mutex> l(mu_);
            return unitsUsed_;
        }

    private:
        struct Request {
            uint64_t unitsRequested;
            ContinuePromise promise;
        };

        Config config_;
        mutable std::mutex mu_;
        uint64_t unitsUsed_{0};
        std::deque<Request> queue_;
    };
} // namespace kumo::pollux::common
